//
//  GoodsList.m
//  RRBI
//
//  Created by kuyuZJ on 16/7/5.
//
//

#import "GoodsList.h"
#import "GoodsListCell.h"
#import "PushGoodsVC.h"
#import "ShopManagerAlertView.h"
#import "MGoods.h"

#define HeaderView_Height  220


@interface GoodsList ()<GoodsListCellDelegate,UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
{
    
    BOOL _isZengXu;
}
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,copy) NSString* cellIdentifier;

//@property(nonatomic,strong) UIView* contentView;
//@property(nonatomic,strong) UIImageView* contentBackground;
//@property(nonatomic,strong) UILabel* labelTitle;
//@property(nonatomic,strong) UIImageView* line;
//@property(nonatomic,strong) UILabel* labelSaleTitle;
//@property(nonatomic,strong) UILabel* labelSalePrice;
//@property(nonatomic,strong) UILabel* labelNewTitle;
//@property(nonatomic,strong) UITextField* txtNewPrice;
//@property(nonatomic,strong) UILabel* labelTip;
//@property(nonatomic,strong) UIButton* btnConfirm;
//@property(nonatomic,strong) UIButton* btnCancel;

@property(nonatomic,strong) NSMutableArray* arrayData;
@property(nonatomic,strong) NetPage* page;

@property(nonatomic,strong) MGoods* currentGoods;



@property(nonatomic,strong) UIView* headerView;
@property(nonatomic,strong) UIButton* typeBtn;
@property(nonatomic,strong) UITextField* searchTF;
@property(nonatomic,strong) UIButton* searchBtn;
@property(nonatomic,strong) NSMutableArray* selectedArray;
@property(nonatomic,assign) BOOL  isSelected;
@property(nonatomic,strong) NSString  *type;
@property(nonatomic,assign) BOOL  isStair;//是否是一级菜单


@property(nonatomic,strong) UIButton* moRenBtn;
@property(nonatomic,strong) UIButton* XiaoLiangZengBtn;

@property (nonatomic, copy) NSString *paiType;//1默认排序2增序3降序
@property (nonatomic, strong) UIView *tiShiView;
@property (nonatomic, strong) UILabel *tiShiLabel;

@end


@implementation GoodsList


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [self.tableView.mj_header beginRefreshing];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"TiShiShow"];
    self.navigationItem.title =  @"商品管理";
    self.type = @"";
    self.isStair = NO;
    self.paiType = @"1";
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(0, 0, 60, 25);
    [rightButton setTitle:@"发布商品" forState:UIControlStateNormal];
    [rightButton setTitleColor:getColor(greenBackColor) forState:UIControlStateNormal];
    rightButton.titleLabel.font = kFontNameSize(14);
    [rightButton addTarget:self action:@selector(rightButton) forControlEvents:UIControlEventTouchUpInside];
    //添加到导航条
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.isSelected = NO;
    [self querySelectData];
    [self creatTableView];
//    [self layoutUI];
//    [self layoutConstraints];
}

-(void)rightButton{
    
    PushGoodsVC * controller = [[PushGoodsVC alloc]init];
    controller.isFaBu = YES;
    [self.navigationController pushViewController:controller animated:YES];
}
-(void)creatTableView{
    
    [self creatHeaderView];
    self.cellIdentifier =  @"GoodsListCell";
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.headerView.frame), SCREEN_WIDTH,  CGRectGetHeight(self.view.frame) -NAVGATIONBAR_HEIGHT - CGRectGetMaxY(self.headerView.frame)) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.separatorColor = [UIColor groupTableViewBackgroundColor];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.view addSubview:self.tableView];
    
    if (@available(iOS 11.0, *))
    {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        self.tableView.estimatedRowHeight = 0;
        self.tableView.estimatedSectionFooterHeight = 0;
        self.tableView.estimatedSectionHeaderHeight = 0;
    }
    [self.tableView registerClass:[GoodsListCell class] forCellReuseIdentifier:self.cellIdentifier];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}
-(void)creatHeaderView{
    
    self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, HeaderView_Height)];
    [self.view addSubview:self.headerView];
    //self.headerView.backgroundColor = [UIColor whiteColor];
    
    UILabel *titleLabel = [[UILabel alloc]init];
    titleLabel.text = @"店铺分类";
//    titleLabel.textColor = [UIColor grayColor];
    titleLabel.font = kFontNameSize(15);
    [self.headerView addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(50);
        make.width.mas_equalTo(100);
        make.left.equalTo(self.headerView).mas_offset(20);
        make.top.equalTo(self.headerView);
    }];
    
    UIImageView *arrowImageView =[[UIImageView alloc] init];
    arrowImageView.image = [UIImage imageNamed:@"icon_arrowright"];
    arrowImageView.contentMode = UIViewContentModeScaleAspectFill;
    [self.headerView addSubview:arrowImageView];
    [arrowImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.headerView).offset(-12);
        make.centerY.equalTo(titleLabel);
        make.size.mas_equalTo(CGSizeMake(20, 20));
        
    }];
    
    
    self.typeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.typeBtn addTarget:self action:@selector(typeBtnAction) forControlEvents:UIControlEventTouchUpInside];
    self.typeBtn.titleLabel.font= kFontNameSize(15);
    self.typeBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [self.headerView addSubview:self.typeBtn];
    [self.typeBtn setTitle:@"请选择店铺分类" forState:UIControlStateNormal];
    [self.typeBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [self.typeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(titleLabel);
        make.left.equalTo(titleLabel.mas_right);
        make.right.equalTo(arrowImageView.mas_left);
    }];
    
    self.searchTF = [[UITextField alloc] init];
    self.searchTF.placeholder = @"请输入您要搜索的商品名称";
    self.searchTF.borderStyle = UITextBorderStyleRoundedRect;
    self.searchTF.font = kFontNameSize(14);
    self.searchTF.delegate = self;
    self.searchTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self.headerView  addSubview:self.searchTF];
    [self.searchTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.headerView).mas_offset(-30);
        make.left.equalTo(self.headerView).mas_offset(30);
        make.top.equalTo(self.typeBtn.mas_bottom);
        make.height.mas_equalTo(40);
        
    }];
    
    
    
    self.searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.searchBtn addTarget:self action:@selector(searchBtnAction) forControlEvents:UIControlEventTouchUpInside];
    self.searchBtn.layer.masksToBounds = YES;
    self.searchBtn.layer.cornerRadius = 5;
    self.searchBtn.titleLabel.font= kFontNameSize(15);
    [self.headerView addSubview:self.searchBtn];
    [self.searchBtn setTitle:@"查询" forState:UIControlStateNormal];
    self.searchBtn.backgroundColor=  getColor(greenBackColor);
    [self.searchBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.searchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.searchTF.mas_bottom).offset(10);
        make.height.mas_equalTo(50);
        make.right.equalTo(self.headerView).mas_offset(-30);
        make.left.equalTo(self.headerView).mas_offset(30);
    }];
    
    
    self.moRenBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, self.headerView.bounds.size.height-40, 80, 40)];
    [self.moRenBtn setTitle:@"默认排序" forState:UIControlStateNormal];
    self.moRenBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    [self.moRenBtn setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
    [self.moRenBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.headerView addSubview:self.moRenBtn];
    self.moRenBtn.selected = YES;
    
    
    self.XiaoLiangZengBtn = [[UIButton alloc]initWithFrame:CGRectMake(80+30, self.headerView.bounds.size.height-40, 44, 40)];
    [self.XiaoLiangZengBtn setImage:[UIImage imageNamed:@"未点击"] forState:UIControlStateNormal];
    [self.headerView addSubview:self.XiaoLiangZengBtn];
    
    
     [self.moRenBtn addTarget:self action:@selector(moRenBtnBtnACtion) forControlEvents:UIControlEventTouchUpInside];
    [self.XiaoLiangZengBtn addTarget:self action:@selector(XiaoLiangZengBtnACtion) forControlEvents:UIControlEventTouchUpInside];
    
    [self createTiShiViewUI];
    
}

- (void)createTiShiViewUI {
    [self.tiShiView removeFromSuperview];
    self.tiShiView = [[UIView alloc]initWithFrame:CGRectMake(30, self.headerView.bounds.size.height-40-70, SCREEN_WIDTH- 60, 50)];
    self.tiShiView.layer.masksToBounds = YES;
    self.tiShiView.layer.cornerRadius = 5;
    self.tiShiView.backgroundColor = [UIColor colorWithRed:253.0/255.0 green:174.0/255.0 blue:18.0/255.0 alpha:1];
    [self.headerView addSubview:self.tiShiView];
    
    self.tiShiLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, self.tiShiView.bounds.size.width-30, 50)];
    self.tiShiLabel.textColor = [UIColor whiteColor];
    self.tiShiLabel.text = [NSString stringWithFormat:@"温馨提示:无"];
    self.tiShiLabel.font = [UIFont systemFontOfSize:14];
    [self.tiShiView addSubview:self.tiShiLabel];
    
    UIButton *chaButton = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-40, self.headerView.bounds.size.height-40-70-10, 25, 25)];
    chaButton.tag = 100;
    [chaButton addTarget:self action:@selector(chaButtonACtion) forControlEvents:UIControlEventTouchUpInside];
    [chaButton setImage:[UIImage imageNamed:@"x"] forState:UIControlStateNormal];
    [self.headerView addSubview:chaButton];
    
    [self showTiShiView];
    
}
- (void)chaButtonACtion {
    
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"TiShiShow"];
    self.tiShiView.hidden = YES;
    
    self.headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, HeaderView_Height);
    self.tiShiView.frame = CGRectMake(30, self.headerView.bounds.size.height-40-70, SCREEN_WIDTH- 60, 50);
    self.moRenBtn.frame =CGRectMake(0, self.headerView.bounds.size.height-40, 80, 40);
    self.XiaoLiangZengBtn.frame =CGRectMake(80+30, self.headerView.bounds.size.height-40, 44, 40);
    self.tableView.frame =CGRectMake(0, CGRectGetMaxY(self.headerView.frame), SCREEN_WIDTH,  CGRectGetHeight(self.view.frame)  - self.headerView.bounds.size.height);
    UIButton *chaButton = [self.view viewWithTag:100];
    chaButton.frame  = CGRectMake(SCREEN_WIDTH-40, self.headerView.bounds.size.height-40-70-10, 25, 25);
    chaButton.hidden = YES;
    
}

- (void)showTiShiView {
    self.tiShiView.hidden = NO;
    self.headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, HeaderView_Height+70);
    self.tiShiView.frame = CGRectMake(30, self.headerView.bounds.size.height-40-70, SCREEN_WIDTH- 60, 50);
    self.moRenBtn.frame =CGRectMake(0, self.headerView.bounds.size.height-40, 80, 40);
    self.XiaoLiangZengBtn.frame =CGRectMake(80+30, self.headerView.bounds.size.height-40, 44, 40);
    
    self.tableView.frame =CGRectMake(0, CGRectGetMaxY(self.headerView.frame), SCREEN_WIDTH,  CGRectGetHeight(self.view.frame)  - self.headerView.bounds.size.height);
    UIButton *chaButton = [self.view viewWithTag:100];
    chaButton.frame  = CGRectMake(SCREEN_WIDTH-40, self.headerView.bounds.size.height-40-70-10, 25, 25);
    chaButton.hidden = NO;
}
//默认排序
- (void)moRenBtnBtnACtion{
    self.moRenBtn.selected = YES;
    _isZengXu = NO;
    [self.XiaoLiangZengBtn setImage:[UIImage imageNamed:@"未点击"] forState:UIControlStateNormal];//全黑色
    self.paiType = @"0";
    [self refreshDataSource];
}
//增序
- (void)XiaoLiangZengBtnACtion {
    self.moRenBtn.selected = NO;
    
    _isZengXu = !_isZengXu;
    if (_isZengXu) {
        self.paiType = @"2";
        [self.XiaoLiangZengBtn setImage:[UIImage imageNamed:@"升序-1"] forState:UIControlStateNormal];//增序
    } else {
        self.paiType = @"1";
        [self.XiaoLiangZengBtn setImage:[UIImage imageNamed:@"降序-1"] forState:UIControlStateNormal];//降序
    }
    
    [self refreshDataSource];
}

-(void)querySelectData{
    //    "ince":"getshopcat","sid":"101","parent_id":"0",
    NSDictionary* arg = @{@"ince":@"getshopcat",
                          @"sid":[UserModel sharedInstanced].ru_Id,
                          @"parent_id":@"0"
                          };

    
    [NetRepositories netConfirm:arg complete:^(EnumNetResponse react,NSDictionary* response ,NSString *message) {
        if(react == NetResponseSuccess){
        
            self.selectedArray = [response objectForKey:@"data"];
            
            NSDictionary *dict = self.selectedArray.firstObject;
            NSMutableArray *cityArr = [dict objectForKey:@"son"];
            if (cityArr.count >0 ) {
                self.isStair = NO;
            }else{
                self.isStair = YES;
            }
          
            [self refreshDataSource];
            
        }else if (react == NetResponseException){
            ShowMessage(message);
        }else{
            ShowMessage(message);
        }
    }];
    
    
    
}

-(void)typeBtnAction{
    
    [self.view endEditing:YES];
    
    if (!self.isStair) {
        
        [CGXPickerView showAddressPickerWithTitle:@"店铺分类" DataSource:self.selectedArray DefaultSelected:@[@0, @0,@0] IsAutoSelect:NO Manager:nil ResultBlock:^(NSArray *selectAddressArr, NSArray *selectAddressRow ,NSString *code) {
            NSLog(@"%@-%@",selectAddressArr,selectAddressRow);
            NSLog(@"code = %@",code);
            
            self.type = code;
            NSString *textStr = @"";
            if (selectAddressArr.count == 1) {
                textStr = [NSString stringWithFormat:@"%@", selectAddressArr[0]];
                
            }else if (selectAddressArr.count == 2) {
                textStr = [NSString stringWithFormat:@"%@-%@", selectAddressArr[0], selectAddressArr[1]];
                
            }else{
                textStr = [NSString stringWithFormat:@"%@-%@-%@", selectAddressArr[0], selectAddressArr[1],selectAddressArr[2]];
            }
            
            [self.typeBtn setTitle:textStr forState:UIControlStateNormal];
            [self.typeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }];
        
        
    }else{
        
        NSMutableArray *array = [NSMutableArray array];
        
        for (NSDictionary *dic in self.selectedArray) {
            [array addObject:dic[@"cat_name"]];
        }
        
        [CGXPickerView showStringPickerWithTitle:@"店铺分类" DataSource:array DefaultSelValue:array.firstObject IsAutoSelect:NO Manager:nil ResultBlock:^(id selectValue, id selectRow) {
            NSLog(@"%@",selectValue);
            NSLog(@"selectRow = %@",selectRow);
            NSInteger index = [selectRow integerValue];
            NSDictionary *dic = self.selectedArray[index];
            
            self.type = [NSString stringWithFormat:@"%@",dic[@"cat_id"]];
            [self.typeBtn setTitle:[NSString stringWithFormat:@"%@",selectValue] forState:UIControlStateNormal];
            [self.typeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            
            
        }];
        
    }
}

-(void)searchBtnAction{
//    "get_shop_foods","sid":"101","page":"1","type":"1524"
    
    [self.view endEditing:YES];
    
    NSString *searchText = [self.searchTF.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; 
    if ([self.typeBtn.titleLabel.text rangeOfString:@"选择"].location != NSNotFound && [searchText length] == 0) {
        
        ShowMessage(@"请选择店铺分类或者输入商品名称");

        
    }else{
        
        self.isSelected = YES;
        self.page.pageIndex = 1;
        [self queryData];
        
        [self moRenBtnBtnACtion];
    }
 
}
#pragma mark =====================================================  Data Source
-(void)queryData{
    
    NSString *searchText = [self.searchTF.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

    
    NSDictionary *arg = [NSDictionary dictionary];

    if (self.isSelected) {
        arg = @{@"ince":@"get_shop_foods",
                @"type":self.type,
                @"keywords":searchText,
                @"sid":[UserModel sharedInstanced].ru_Id,
                @"page":[WMHelper integerConvertToString:self.page.pageIndex],
                @"sort":self.paiType
                };
    }else{
        arg = @{@"ince":@"get_shop_foods",
                @"sid":[UserModel sharedInstanced].ru_Id,
                @"page":[WMHelper integerConvertToString:self.page.pageIndex],
                @"sort":self.paiType
                };
        
    }
    [NetRepositories queryGoods:arg page:self.page complete:^(EnumNetResponse react, NSArray *list, NSString *message, NSDictionary *mainDict) {
        
        self.tiShiLabel.text = [mainDict objectForKey:@"qh_msg"];
        
        if ([[NSUserDefaults standardUserDefaults] boolForKey:@"TiShiShow"]) {
            if ([[mainDict objectForKey:@"qh_msg"] isEqualToString:@""]) {
                [self chaButtonACtion];
            } else {
                [self showTiShiView];
            }
        }
        
        
        if(self.page.pageIndex == 1){
            [self.arrayData removeAllObjects];
        }
        if(react == NetResponseSuccess){
            
            //self.arrayData = [MGoods mj_objectArrayWithKeyValuesArray:list];
            NSMutableArray *tempArr = [NSMutableArray array];
            tempArr = [MGoods mj_objectArrayWithKeyValuesArray:list];
            [self.arrayData addObjectsFromArray:tempArr];
//            [list enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//                [self.arrayData addObject:obj];
//            }];
        }else if(react == NetResponseException){
            [self alertHUD:message];
        }else{
            [self alertHUD:message];
        }
        
        [self.tableView reloadData];
        if(self.page.pageCount<=self.page.pageIndex){
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }else{
            [self.tableView.mj_footer endRefreshing];
        }
        if(self.page.pageIndex==1){
            [self.tableView.mj_header endRefreshing];
        }
        
    }];
    
}
-(void)refreshDataSource{
    [self.tableView.mj_footer endRefreshing];
    [self.tableView.mj_header endRefreshing];
    [self.tableView setContentOffset:CGPointMake(0,0) animated:YES];
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.page.pageIndex = 1;
        [weakSelf queryData];
    }];
    
    self.tableView.mj_footer = [MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
        weakSelf.page.pageIndex ++;
        [weakSelf queryData];
    }];
    [self.tableView.mj_header beginRefreshing];
}


#pragma mark =====================================================  <UITableViewDataSource>
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.arrayData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    GoodsListCell* cell = [tableView dequeueReusableCellWithIdentifier:self.cellIdentifier forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.delegate = self;
    cell.entity = self.arrayData[indexPath.row];

    return cell;
}

#pragma mark =====================================================  <UITableViewDelegate>
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    MGoods* item = self.arrayData[indexPath.row];
    CGFloat width = SCREEN_WIDTH - 150.f;
    CGFloat height = [WMHelper calculateTextHeight:item.goodsName font:[UIFont systemFontOfSize:14.f] width:width];
    if(height>35.f){
        return 35.f+height;
    }
    return 70.f;
}

#pragma mark =====================================================  <GoodsListCellDelegate>
-(void)updateGoodsImage:(MGoods*)sender{
    if(sender){
        self.currentGoods = sender;
        [self updateAvatarImage];
    }
    
}
-(void)updateGoodsTitle:(MGoods*)sender{
    if(sender){
        self.currentGoods = sender;
        ShopManagerAlertView *alertView = [[ShopManagerAlertView alloc] initAlertWithType:ShopManagerTitle withText:sender.goodsName];
        //            __weak typeof(alertView) weakAlert = alertView;
        alertView.resultIndex = ^(NSString * _Nonnull changeText) {
            NSDictionary* arg =  @{@"ince":@"set_shop_name",
                                   @"sid":[UserModel sharedInstanced].ru_Id,
                                   @"fid": self.currentGoods.fid,
                                   @"name":changeText
                                   };
            [NetRepositories netConfirm:arg complete:^(EnumNetResponse react,NSDictionary* response ,NSString *message) {
                if(react == NetResponseSuccess){
                    //                    ShowMessage(message);
                    NSString* name = [response objectForKey: @"goods_name"];
                    self.currentGoods.goodsName = name;
                    [self.tableView.mj_header beginRefreshing];
                }else if (react == NetResponseException){
                    ShowMessage(message);
                }else{
                    ShowMessage(message);
                }
            }];
            
        };
        [alertView showAlertView];
        
    }
    
}
-(void)updateGoodsPrice:(MGoods *)sender{
    if(sender){
        self.currentGoods = sender;
        
            PushGoodsVC * controller = [[PushGoodsVC alloc]init];
            controller.isFaBu = NO;
        controller.goodsId = sender.fid;
            [self.navigationController pushViewController:controller animated:YES];
//        ShopManagerAlertView *alertView = [[ShopManagerAlertView alloc] initAlertWithType:ShopManagerPrice withText:self.currentGoods.price];
//        //            __weak typeof(alertView) weakAlert = alertView;
//        alertView.resultIndex = ^(NSString * _Nonnull changeText) {
//            NSDictionary* arg =  @{@"ince":@"set_shop_foodprice",
//                                   @"sid":[UserModel sharedInstanced].ru_Id,
//                                   @"fid": self.currentGoods.rowID,
//                                   @"price":changeText
//                                   };
//            [NetRepositories netConfirm:arg complete:^(EnumNetResponse react,NSDictionary* response ,NSString *message) {
//                if(react == NetResponseSuccess){
////                    ShowMessage(message);
//                    NSString* price = [response objectForKey: @"price"];
//                    NSString* checkPrice = [response objectForKey: @"check_price"];
//                    self.currentGoods.price = price;
//                    self.currentGoods.checkPrice = checkPrice;
//                    [self.tableView reloadData];
//                }else if (react == NetResponseException){
//                    ShowMessage(message);
//                }else{
//                    ShowMessage(message);
//                }
//            }];
//
//
//        };
//        [alertView showAlertView];
        
        
//        self.currentGoods = sender;
//        self.labelSalePrice.text = self.currentGoods.price;
//        self.HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
//        [self.navigationController.view addSubview:self.HUD];
//        self.HUD.delegate = self;
//        self.HUD.dimBackground = YES;
//        self.HUD.color = [UIColor clearColor];
//        self.HUD.mode = MBProgressHUDModeCustomView;
//        self.HUD.customView  =self.contentView;
//        [self.HUD showAnimated:YES];
    }
}
-(void)publishGoods:(MGoods *)sender{
    if(sender){
        self.currentGoods = sender;
        NSString* empty = [NSString stringWithFormat: @"您确认要%@该商品吗？",[self.currentGoods.status integerValue]==0? @"上架": @"下架"];
        UIAlertController *av = [UIAlertController alertControllerWithTitle:empty message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSString* status = [self.currentGoods.status integerValue]==0? @"1": @"0";
            NSDictionary* arg =  @{@"ince":@"set_shop_foodstatus",@"sid":[UserModel sharedInstanced].ru_Id, @"fid": self.currentGoods.fid, @"status":status};
            [NetRepositories updtaeGoods:arg complete:^(EnumNetResponse react, NSString *message) {
                if(react == NetResponseSuccess){
                    [self alertHUD: @"操作成功!"];
                }else if (react == NetResponseException){
                    [self alertHUD:message];
                }else{
                    [self alertHUD:message];
                }
                self.currentGoods = nil;
                [self.tableView.mj_header beginRefreshing];
            }];
        }];
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [av addAction:action1];
        [av addAction:action2];
        [self presentViewController:av animated:YES completion:nil];
        
        
    }
}

#pragma mark - 上传头像
- (void)updateAvatarImage
{
    
    self.navigationController.navigationBar.hidden = NO;
    UIAlertController *alertSheet = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.navigationBar.translucent = NO;
    imagePickerController.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
    imagePickerController.allowsEditing = YES;
    
    // 判断是否支持相机
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            // 设置数据源
            imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:imagePickerController animated:YES completion:nil];
        }];
        [alertSheet addAction:cameraAction];
    }
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
    {
        UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:imagePickerController animated:YES completion:nil];
        }];
        [alertSheet addAction:photoAction];
    }
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertSheet addAction:cancelAction];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self presentViewController:alertSheet animated:YES completion:nil];
    });
    
    
}



#pragma mark UIImagePickerControllerDelegate

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:@"public.image"])        // 被选中的图片
    {
        // 获取照片
        UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
        [picker dismissViewControllerAnimated:YES completion:nil];          // 隐藏视图
        
        [self commitUserAvatarDataWithImage:image];
    }
}

#pragma mark - 提交用户头像
-(void)commitUserAvatarDataWithImage:(UIImage *)image{
    
    NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setValue:@"arr" forKey:@"ince"];
    [dic setValue:[UserModel sharedInstanced].ru_Id forKey:@"sid"];
    
    [NetRepositories requestAFURL:dic imageData:imageData complete:^(EnumNetResponse react, NSDictionary *response, NSString *message) {
        
        NSLog(@"response = %@",response);
        ShowMessage(response[@"msg"]);
        
                NSString *original = response[@"original_img"];
                NSString *url = response[@"url"];
                NSString *goods = response[@"goods_img"];
       
        NSDictionary* arg =  @{@"ince":@"update_goods_img",
                               @"sid":[UserModel sharedInstanced].ru_Id,
                               @"goods_id": self.currentGoods.fid,
                               @"url":url,
                               @"goods_img":goods,
                               @"original_img":original
                               };
        [NetRepositories netConfirm:arg complete:^(EnumNetResponse react,NSDictionary* response ,NSString *message) {
            if(react == NetResponseSuccess){
                ShowMessage(message);
                NSString* iamge = [response objectForKey: @"goods_img"];
                self.currentGoods.thumbnail = iamge;
                [self.tableView reloadData];
            }else if (react == NetResponseException){
                ShowMessage(message);
            }else{
                ShowMessage(message);
            }
        }];
          
    }];
    
}


#pragma mark =====================================================  property pacakge
-(NSMutableArray *)arrayData{
    if(!_arrayData){
        _arrayData = [[NSMutableArray alloc]init];
    }
    return _arrayData;
}

-(NSMutableArray *)selectedArray{
    
    if (!_selectedArray) {
        _selectedArray = [[NSMutableArray alloc]init];

    }

    return  _selectedArray;
}
-(NetPage *)page{
    if(!_page){
        _page = [[NetPage alloc]init];
        _page.pageIndex = 1;
    }
    return _page;
}

@end
